package net.chrisrichardson.ec2deployer.cluster

import org.apache.commons.logging.*
import net.chrisrichardson.ec2deployer.core.AWSProperties
import net.chrisrichardson.ec2deployer.core.EC2


class ClusterManager {

    def Log logger = LogFactory.getLog(getClass())
    def awsProperties
    ClusterDefinitionManager clusterDefinitionManager

    def static reuseRunningInstancesForDebugging = false

    def ClusterManager(AWSProperties awsProperties) {
        this.awsProperties = awsProperties
        this.clusterDefinitionManager = new ClusterDefinitionManager()
    }

    def defineCluster(clusterName, ClusterSpec clusterSpec) {
        def clusterDefinition = new ClusterDefinition(clusterName, clusterSpec)
        clusterDefinitionManager.saveDefinition(clusterDefinition)
    }


    def getCluster(clusterName) {
        ClusterDefinition definition = clusterDefinitionManager.findDefinition(clusterName)
        def ec2 = new EC2(awsProperties)
        new SimpleCluster(ec2, definition)
    }

    def startCluster(String clusterName) {
        SimpleCluster cluster = getCluster(clusterName)
        cluster.start(reuseRunningInstancesForDebugging)
        saveCluster(clusterName, cluster)
    }

    def saveCluster(clusterName, cluster) {
        clusterDefinitionManager.saveDefinition(new ClusterDefinition(clusterName, cluster.spec, cluster.serverState))
    }
    
    def removeCluster(String clusterName) {
        clusterDefinitionManager.removeCluster(clusterName)
    }

    List<String> listClusters() {
        clusterDefinitionManager.listClusters()
    }

    def cloneCluster(cluster, newName) {
        // check that name is not used
        def newCluster = cluster.cloneCluster()
        saveCluster(newName, newCluster)
    }

}